package com.cclinux.projects.actcampus.controller.admin;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cclinux.framework.annotation.DemoShow;
import com.cclinux.framework.annotation.LoginIgnore;
import com.cclinux.framework.core.domain.ApiResult;
import com.cclinux.framework.core.domain.PageParams;
import com.cclinux.framework.core.domain.PageResult;
import com.cclinux.framework.core.mapper.UpdateWhere;
import com.cclinux.framework.core.mapper.Where;
import com.cclinux.framework.helper.FormHelper;
import com.cclinux.framework.helper.TimeHelper;
import com.cclinux.framework.validate.DataCheck;
import com.cclinux.projects.actcampus.mapper.*;
import com.cclinux.projects.actcampus.model.*;
import com.cclinux.projects.actcampus.service.admin.AdminActivityService;
import com.cclinux.projects.actcampus.service.cust.ActivityService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController("ActCampusAdminFeeController")
public class AdminFeeController extends BaseMyAdminController {

    @Resource(name = "ActCampusAdminActivityService")
    private AdminActivityService adminActivityService;

    @Resource(name = "ActCampusActivityMapper")
    private ActivityMapper activityMapper;

    @Resource(name = "ActCampusActivityService")
    private ActivityService activityService;

    @Resource(name = "ActCampusActivityClassMapper")
    private ActivityClassMapper activityClassMapper;

    @Resource(name = "ActCampusActivityJoinClassMapper")
    private ActivityJoinClassMapper activityJoinClassMapper;

    @Resource(name = "ActCampusActivityJoinMapper")
    private ActivityJoinMapper activityJoinMapper;

    @Resource(name = "ActCampusActivityJoinClassFeeMapper")
    private ActivityJoinClassFeeMapper activityJoinClassFeeMapper;

    @Resource(name = "ActCampusUserMapper")
    private UserMapper userMapper;

    @LoginIgnore
    @RequestMapping(value = "/admin/fee/list")
    public ApiResult getAdminActivityList(@RequestBody Map<String, Object> input,
                                          @RequestParam("userId") Integer userId,
                                          @RequestParam("joinId") Integer joinId) {

        // 加入的joinId，通过joinId查询对应的活动id

        ActivityJoinModel activityJoinModel = activityJoinMapper.selectById(joinId);
        ActivityModel activityModel = activityMapper.selectById(activityJoinModel.getActivityJoinActivityId());


        // 业务
        Where<ActivityJoinClassFeeModel> where = new Where<>();
        where.eq("ACTIVITY_JOIN_USER_ID", userId);
        where.eq("ACTIVITY_JOIN_ID", joinId);
        where.eq("ACTIVITY_JOIN_ACTIVITY_ID", activityModel.getActivityId());
        where.eq("ACTIVITY_JOIN_STATUS", 0);

        where.orderByDesc("ACTIVITY_JOIN_CLASS_FEE_ID");


        Page page = new Page(0, 1000);

        PageResult pageResult = activityJoinClassFeeMapper.getPageList(page, where, "*");

        List<Map<String, Object>> list = pageResult.getList();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        list.stream().forEach(e -> {
            e.put("activityTitle", activityModel.getActivityTitle());

            try {

                UserModel userModel = userMapper.getOne(userId);
                String addTime = e.get("addTime").toString();
                e.put("addTime", dateFormat.format(dateFormat.parse(addTime)));
                e.put("userMobile", userModel.getUserAccount());
            } catch (Exception ex) {
                ex.printStackTrace();
            }

//            e.setActivityTitle(activityModel.getActivityTitle());
        });

        return ApiResult.success(pageResult);
    }


    @LoginIgnore
    @RequestMapping(value = "/admin/fee/joinClass/status")
    public ApiResult statusActivityJoinClassStatus(@RequestBody Map<String, Object> input) {

        // 数据校验
        String[] RULES = {
                "id:must|long",
                "status:must|int|name=状态"
        };
        DataCheck.check(input, RULES);

        // 业务
        long id = MapUtil.getLong(input, "id");
        int status = MapUtil.getInt(input, "status");

        UpdateWhere<ActivityJoinClassModel> uw = new UpdateWhere<>();
        uw.eq("ACTIVITY_JOIN_CLASS_ID", id);
        uw.set("ACTIVITY_USE_STATUS", status);
        activityJoinClassMapper.edit(uw);


        ActivityJoinClassModel activityJoinClassModel = activityJoinClassMapper.selectById(id);
        long userId = activityJoinClassModel.getActivityJoinUserId();
        List<ActivityJoinClassModel> list = activityClassMapper.selectByJoinIdAndClassIdNoUseStatus(activityJoinClassModel.getActivityJoinId(), userId);
        PageResult ret = new PageResult();


        ObjectMapper mapper = new ObjectMapper();
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Object obj : list) {
            try {
                String json = mapper.writeValueAsString(obj);
                Map<String, Object> map = mapper.readValue(json, Map.class);
                mapList.add(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        ret.setList(mapList);

        return ApiResult.success(ret);
    }

    @LoginIgnore
    @RequestMapping(value = "/admin/fee/del")
    public ApiResult delActivity(@RequestBody Map<String, Object> input) {

        // 数据校验
        String[] RULES = {
                "id:must|long"
        };
        DataCheck.check(input, RULES);

        // 业务
        long activityId = MapUtil.getLong(input, "id");
        adminActivityService.delActivity(activityId);

        return ApiResult.success();
    }

    @LoginIgnore
    @RequestMapping(value = "/admin/fee/insert")
    public ApiResult insertActivity(@RequestBody Map<String, Object> input) {

        // 业务
        Integer userId = Integer.valueOf(input.get("userId").toString());
        Integer joinId = Integer.valueOf(input.get("joinId").toString());
        Double feeValue = Double.valueOf(input.get("inputFeeValue").toString());

        ActivityJoinClassFeeModel feeModel = new ActivityJoinClassFeeModel();
        feeModel.setFee(feeValue);
        feeModel.setActivityTitle(input.get("activityTitle").toString());
        feeModel.setActivityJoinUserId(userId);
        feeModel.setActivityJoinActivityId(activityJoinMapper.selectById(joinId).getActivityJoinActivityId());
        feeModel.setActivityJoinId(joinId);
        feeModel.setUserMobile(input.get("userMobile").toString());

        // 判断消费金额不超过总金额
        Where<ActivityJoinClassFeeModel> where = new Where<>();
        where.eq("ACTIVITY_JOIN_USER_ID", userId);
        List<ActivityJoinClassFeeModel> feeModelList = activityJoinClassFeeMapper.getAllList(where, "*");
        if (!CollectionUtils.isEmpty(feeModelList)) {
            double sumFee = feeModelList.stream().mapToDouble(ActivityJoinClassFeeModel::getFee).sum();
            UserModel userModel = userMapper.getOne(userId);

            if (userModel.getRmb() < sumFee + feeValue) {
                return ApiResult.error("消费累计金额大于总金额");
            }
        }

        int id = activityJoinClassFeeMapper.insert(feeModel);

        return ApiResult.success(MapUtil.of("id", id));
    }



}
